package com.hifar.test.structure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hifar.fw.utils.lang.NumberUtils;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.log.AutoLogUtils;
import com.hifar.plat.AopOption.DictModel;
import com.hifar.plat.baseModal.pojo.BaseOssFiles;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.baseModal.service.IBaseSysDictClassifyService;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.sys.BusiResponse;
import com.hifar.test.structure.mapper.HfEnvResPersonMapper;
import com.hifar.test.structure.pojo.HfEnvResPerson;
import com.hifar.test.structure.pojo.VO.HfEnvResPersonExportVO;
import com.hifar.test.structure.pojo.VO.HfEnvResPersonSaveVO;
import com.hifar.test.structure.service.IHfEnvResPersonService;
import com.hifar.test.structure.service.IHfEnvResPersonWorkRecordService;
import com.hifar.utils.ExcelImportUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class HfEnvResPersonServiceImpl extends ServiceImpl<HfEnvResPersonMapper, HfEnvResPerson>
        implements IHfEnvResPersonService {
    @Autowired
    private IHfEnvResPersonWorkRecordService envResPersonWorkRecordService;
    @Autowired
    private IBaseSysDictClassifyService sysDictClassifyService;

    @Autowired
    private IBaseOssFilesService baseOssFilesService;
    @Autowired
    private AutoLogUtils autoLogUtils;

    @Override
    public void add(HfEnvResPersonSaveVO hfEnvResPersonSaveVO) {
        HfEnvResPerson hfEnvResPerson = new HfEnvResPerson();
        BeanUtils.copyProperties(hfEnvResPersonSaveVO, hfEnvResPerson);
        this.save(hfEnvResPerson);
        String id = hfEnvResPerson.getId();

        List<String> fileIdList = Optional.ofNullable(hfEnvResPersonSaveVO.getFileIdList())
                .orElse(new ArrayList<>(0));

        List<String> evaluateFileIdList = Optional.ofNullable(hfEnvResPersonSaveVO.getEvaluateFileIdList())
                .orElse(new ArrayList<>(0));

        //保存图片
        List<BaseOssFiles> evaluateFileList = Optional.ofNullable(hfEnvResPersonSaveVO.getEvaluateFileList())
                .orElse(new ArrayList<>(0));
        List<BaseOssFiles> fileInfoList = Optional.ofNullable(hfEnvResPersonSaveVO.getFileInfoList())
                .orElse(new ArrayList<>(0));
        for (BaseOssFiles baseOssFiles : evaluateFileList) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType("hf_env_res_person_evaluate");
        }
        for (BaseOssFiles baseOssFiles : fileInfoList) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType("hf_env_res_person");
        }

        UpdateWrapper<BaseOssFiles> updateFileWrapper = new UpdateWrapper<>();
        updateFileWrapper.lambda()
                .set(BaseOssFiles::getRefId, null)
                .eq(BaseOssFiles::getRefId, id)
                .in(BaseOssFiles::getRefType, "hf_env_res_person", "hf_env_res_person_evaluate");
        baseOssFilesService.update(updateFileWrapper);
        baseOssFilesService.updateBatchById(evaluateFileList);
        baseOssFilesService.updateBatchById(fileInfoList);
    }

    @Override
    public void edit(HfEnvResPersonSaveVO hfEnvResPersonSaveVO) {
        HfEnvResPerson hfEnvResPerson = new HfEnvResPerson();
        BeanUtils.copyProperties(hfEnvResPersonSaveVO, hfEnvResPerson);
        this.updateById(hfEnvResPerson);
        String id = hfEnvResPerson.getId();
        //保存图片
        List<BaseOssFiles> evaluateFileList = Optional.ofNullable(hfEnvResPersonSaveVO.getEvaluateFileList())
                .orElse(new ArrayList<>(0));
        List<BaseOssFiles> fileInfoList = Optional.ofNullable(hfEnvResPersonSaveVO.getFileInfoList())
                .orElse(new ArrayList<>(0));
        for (BaseOssFiles baseOssFiles : evaluateFileList) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType("hf_env_res_person_evaluate");
        }
        for (BaseOssFiles baseOssFiles : fileInfoList) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType("hf_env_res_person");
        }

        UpdateWrapper<BaseOssFiles> updateFileWrapper = new UpdateWrapper<>();
        updateFileWrapper.lambda()
                .set(BaseOssFiles::getRefId, null)
                .eq(BaseOssFiles::getRefId, id)
                .in(BaseOssFiles::getRefType, "hf_env_res_person", "hf_env_res_person_evaluate");
        baseOssFilesService.update(updateFileWrapper);
        baseOssFilesService.updateBatchById(evaluateFileList);
        baseOssFilesService.updateBatchById(fileInfoList);
    }

    @Override
    public BusiResponse exportExcel(QueryWrapper<HfEnvResPerson> queryWrapper, String operationType) {
        BusiResponse<Object> response = new BusiResponse<>();

        // 检查是否为模板下载请求
        if (StringUtils.isNotBlank(operationType) && (operationType.equals("template"))) {
            ExcelTemplateUtil.exportExcelTemplate(response, HfEnvResPersonExportVO.class, "导入模板", "人员档案导入数据");
            autoLogUtils.addLog("人员管理-人员档案", "下载人员档案导入模板");
            return response;
        }

        // 原有的数据导出逻辑
        List<HfEnvResPerson> dataList = this.list(queryWrapper);
        Set<Integer> secretLevelSet = new HashSet<>();
        Integer maxSecretLve = secretLevelSet.stream().max(Integer::compareTo).orElse(0);
        Map<String, Object> extMap = new HashMap<>(1);
        extMap.put("secretLve", maxSecretLve);


        List<DictModel> dataSecretList = sysDictClassifyService.queryDictItemsByCode("hf_sys_datasecret");
        Map<String, String> dataSecretMap = dataSecretList.stream()
                .collect(Collectors.toMap(
                        item -> item.getValue(),
                        item -> item.getText(),
                        (o1, o2) -> o1
                ));
        String secretLevelText = dataSecretMap.get(com.hifar.fw.utils.lang.StringUtils.trimNull(maxSecretLve));
        extMap.put("secretLevelText", secretLevelText);
        response.setExt(extMap);

        List<HfEnvResPersonExportVO> exportVoList = dataList.stream()
                .map(item -> {
                    HfEnvResPersonExportVO hfEnvResPersonExportVO = new HfEnvResPersonExportVO();
                    BeanUtils.copyProperties(item, hfEnvResPersonExportVO);
                    Integer sex = item.getSex();
                    String status = item.getStatus();

                    String statusText = Objects.equals("1", status) ? "在职" : Objects.equals("2", status) ? "离职" : "";

                    String sexText = sex == 1 ? "男" : sex == 2 ? "女" : "保密";

                    Integer secretLevel = item.getSecretLevel();

                    String itemSecretLevelText = dataSecretMap.get(StringUtils.trimNull(secretLevel));

                    hfEnvResPersonExportVO.setSecretLevelText(itemSecretLevelText);
                    hfEnvResPersonExportVO.setSexText(sexText);
                    hfEnvResPersonExportVO.setStatusText(statusText);
                    return hfEnvResPersonExportVO;
                }).collect(Collectors.toList());


        ExcelTemplateUtil.exportExcel(response, exportVoList, HfEnvResPersonExportVO.class, "人员档案数据", "人员档案导出");
        autoLogUtils.addLog("人员管理-人员档案", "导出人员档案Excel");
        return response;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public BusiResponse importExcel(MultipartFile file) {
        if (file != null && !file.isEmpty()) {
            List<HfEnvResPersonExportVO> importExcel = null;
            try {
                importExcel = ExcelImportUtils.importExcel(file.getInputStream(), HfEnvResPersonExportVO.class);
                List<HfEnvResPerson> importExcelList = new ArrayList<>();
                if (importExcel != null && importExcel.size() > 0) {


                    List<DictModel> dataSecretList = sysDictClassifyService.queryDictItemsByCode("hf_sys_datasecret");
                    Map<String, String> dataSecretMap = dataSecretList.stream()
                            .collect(Collectors.toMap(
                                    item -> item.getText(),
                                    item -> item.getValue(),
                                    (o1, o2) -> o2
                            ));


                    for (HfEnvResPersonExportVO item : importExcel) {
                        HfEnvResPerson hfEnvResPerson = new HfEnvResPerson();
                        BeanUtils.copyProperties(item, hfEnvResPerson);
                        String secretLevelText = item.getSecretLevelText();
                        String statusText = item.getStatusText();
                        String sexText = item.getSexText();

                        int secretLevel = NumberUtils.parseInt(dataSecretMap.get(secretLevelText), 1);
                        hfEnvResPerson.setSecretLevel(secretLevel);

                        String status = Objects.equals("在职", statusText) ? "1" : Objects.equals("离职", statusText) ? "2" : "";
                        hfEnvResPerson.setStatus(status);

                        Integer sex = Objects.equals("男", sexText) ? 1 : Objects.equals("女", sexText) ? 2 : null;
                        hfEnvResPerson.setSex(sex);
                        importExcelList.add(hfEnvResPerson);
                    }
                    this.saveBatch(importExcelList);
                    return BusiResponse.ok("导入成功！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return BusiResponse.error("导入失败，原因未知！");
    }
}




